﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using JBeamLibrary;
using JBeamLibrary.VehicleParts;

namespace DriveBeamEditor.Controls.BeamNG.VehiclePartConfig
{
    public partial class VehiclePartControl : UserControl
    {
        #region Fields

        private VehiclePart _vehiclePart;

        public event EventHandler VehiclePartChanged;

        #endregion

        #region Properties

        public VehiclePart VehiclePart
        {
            get { return _vehiclePart; }
            set
            {
                if (_vehiclePart == value) return;
                _vehiclePart = value;
                OnVehiclePartChanged();
            }
        }

        public VehicleFile VehicleFile
        {
            get { return VehiclePart != null ? VehiclePart.File : null; }
        }

        public Vehicle Vehicle
        {
            get { return VehicleFile != null ? VehicleFile.Parent : null; }
        }

        protected BindingSource VehiclePartSource
        {
            get { return vehiclePartSource; }
        }

        public Icon Icon
        {
            get;
            set;
        }

        #endregion

        #region CTORs

        public VehiclePartControl()
        {
            InitializeComponent();
        }

        #endregion

        #region Events

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            UpdateUI();
        }

        #endregion

        #region Methods

        protected virtual void BindVehiclePart()
        {
            vehiclePartSource.Clear();
            if (VehiclePart == null) return;

            vehiclePartSource.DataSource = VehiclePart;
            vehiclePartSource.ResetBindings(true);
        }

        public virtual void UpdateUI(Control parent = null)
        {
            if (parent == null) parent = this;
            foreach (var control in parent.Controls.Cast<Control>())
            {
                if (control is TextBox || control is Label || control is Button) control.Enabled = VehiclePart != null;
                else UpdateUI(control);
            }
        }

        protected virtual void OnVehiclePartChanged()
        {
            BindVehiclePart();
            UpdateUI();

            if (VehiclePartChanged != null)
                VehiclePartChanged(this, new EventArgs());
        }

        public virtual void RefreshData()
        {
            OnVehiclePartChanged();
        }

        #endregion
    }
}
